package org.argus.common.core.json;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;

import java.math.BigInteger;

/**
 * 将Http响应中的Long转换成String的 ObjectMapper，解决前端JS精度丢失问题
 * @Author 刘文/Cliff Liu
 * @Date 2024/5/14
 */
public class LongToStringObjectMapper extends ObjectMapper {

    public LongToStringObjectMapper() {
        super();
        this.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);
        this.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
        this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        this.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(BigInteger.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.class, LongJavaScriptSafeSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, LongJavaScriptSafeSerializer.instance);
        simpleModule.addSerializer(long.class, LongJavaScriptSafeSerializer.instance);
        registerModule(simpleModule);
    }
}